<template>
  <q-dialog v-model="dialogVisible" full-height full-width>
    <div class="q-preview column no-wrap">
      <div class="q-preview-tip q-px-md text-subtitle1 glossy text-white flex justify-between items-center">
        {{ getName || `${$t('ImagePreview')}` }}
        <q-btn v-close-popup class="q-btn-close" dense flat icon="close" round>
          <q-tooltip v-bind="$tooltipAttr">{{ $t('Close') }}</q-tooltip>
        </q-btn>
      </div>

      <q-carousel v-model="slide" animated class="col bg-transparent" infinite swipeable thumbnails
                  transition-next="slide-left" transition-prev="slide-right">
        <q-carousel-slide v-for="(img, i) in imgList || []" :key="i" :img-src="getSrc(img)" :name="i"
                          class="bg-transparent">
          <img :src="getSrc(img)" :style="imgStyle" alt="" class="rounded-borders" />
        </q-carousel-slide>
      </q-carousel>

      <div class="q-preview-tip glossy text-white flex justify-center items-center q-gutter-x-xl">
        <q-btn dense flat icon="loupe" round @click="zoomImg(1.1)"></q-btn>
        <q-btn dense flat icon="remove_circle_outline" round @click="zoomImg(.9)"></q-btn>
        <q-btn dense flat icon="restore" round @click="restore"></q-btn>
        <q-btn dense flat icon="rotate_left" round @click="rotateImg(-45)"></q-btn>
        <q-btn dense flat icon="rotate_right" round @click="rotateImg(45)"></q-btn>
      </div>
    </div>
  </q-dialog>
</template>

<script setup>
import { computed, ref, watchEffect } from 'vue'

const props = defineProps({ name: String, index: Number, imgList: Array, keyWords: String, modalValue: Boolean })

const scale = ref(1)
const rotate = ref(0)
const dialogVisible = ref('false')
const slide = ref(props.index || 0)
const getName = computed(() => {
  if (!props.imgList || !props.imgList[slide.value]) return
  return props.imgList[slide.value][props.name || 'name']
})

watchEffect(() => {
  slide.value = props.index || 0
})

const getSrc = computed(() => {
  return img => {
    if (typeof img === 'string') return img
    if (props.keyWords) {
      const list = (props.keyWords || '').split('.')
      let src
      for (const str of list) src = src ? src[str] : img[str]
      return src
    }
    return img.src
  }
})
const imgStyle = computed(() => ({ transform: `scale(${scale.value}) rotate(${rotate.value}deg)` }))

const zoomImg = val => scale.value *= val
const rotateImg = val => (rotate.value += val)
const restore = () => {
  scale.value = 1
  rotate.value = 0
}

</script>